const express = require('express');
const router = express.Router();
const { generateSudoku, isValid, getSolution } = require('../utils/sudokuGenerator');

// 生成新游戏
router.get('/new-game', (req, res) => {
    try {
        const { difficulty } = req.query;
        const board = generateSudoku(difficulty);
        res.json({ board });
    } catch (error) {
        console.error('生成数独游戏失败:', error);
        res.status(500).json({ error: '生成游戏失败' });
    }
});

// 验证答案
router.post('/validate', (req, res) => {
    try {
        const { board } = req.body;
        
        // 验证每个单元格
        for (let i = 0; i < 9; i++) {
            for (let j = 0; j < 9; j++) {
                if (board[i][j] === 0) {
                    return res.json({ valid: false, message: '还有空格未填写' });
                }
                
                const temp = board[i][j];
                board[i][j] = 0;
                if (!isValid(board, i, j, temp)) {
                    return res.json({ valid: false, message: '答案不正确' });
                }
                board[i][j] = temp;
            }
        }
        
        res.json({ valid: true, message: '恭喜！答案正确！' });
    } catch (error) {
        res.status(500).json({ error: '验证答案失败' });
    }
});

// 获取提示
router.post('/hint', (req, res) => {
    try {
        const { board, remainingHints } = req.body;
        
        if (remainingHints <= 0) {
            return res.json({ 
                error: true, 
                message: '提示次数已用完' 
            });
        }

        const solution = getSolution(board);
        if (!solution) {
            return res.json({
                error: true,
                message: '无法生成提示'
            });
        }

        // 找到一个空格或错误的格子
        for (let i = 0; i < 9; i++) {
            for (let j = 0; j < 9; j++) {
                if (board[i][j] === 0 || board[i][j] !== solution[i][j]) {
                    return res.json({
                        hint: {
                            row: i,
                            col: j,
                            value: solution[i][j]
                        },
                        remainingHints: remainingHints - 1
                    });
                }
            }
        }

        res.json({
            error: true,
            message: '当前没有可用的提示'
        });
    } catch (error) {
        res.status(500).json({ error: '获取提示失败' });
    }
});

module.exports = router; 